<template>
  <!-- 有账号未绑定qq -->
  <!-- 替换form 绑定校验规则对象 取出错误提示对象 -->
  <Form ref="form" class="xtx-form" :validation-schema="rules" v-slot="{errors}">
    <!-- 测试 -->
    <!-- <p>{{errors}}</p> -->
    <div class="user-info">
      <img :src="userQQ.photo" alt="" />
      <p>Hi，{{userQQ.name}} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <!-- 替换input 双向绑定表单数据  name指定校验函数 动态添加错误提示框类名-->
        <Field v-model="formData.mobile" name="mobile" :class="{err:errors.mobile}" class="input" type="text" placeholder="绑定的手机号" />
      </div>
      <!-- 错误提示信息 -->
      <div class="error" v-show="errors.mobile">{{errors.mobile}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field v-model="formData.code" name="code" :class="{err:errors.code}" class="input" type="text" placeholder="短信验证码" />
        <span class="code" @click="sendCode">{{count===0?'发送验证码':`${count}秒后重发`}}</span>
      </div>
      <!-- 错误提示信息 -->
      <div class="error" v-show="errors.code">{{errors.code}}</div>
    </div>
    <a href="javascript:;" class="submit" @click="bindQQ">立即绑定</a>
  </Form>
</template>

<script>
import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import { reactive, ref } from 'vue'
import { useCountDown } from '@/hook'
import { userQQBindCode, userQQBindLogin } from '@/api/user'
import { message } from '@/components/Message/index.js'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
// 获取qq用户信息
const useQQ = () => {
  const userQQ = ref({
    name: '',
    photo: ''
  })

  // qq是否登录
  if (window.QC.Login.check()) {
    // 调用腾讯接口获取qq用户信息
    window.QC.api('get_user_info').success((res) => {
      // console.log(res)
      userQQ.value.name = res.data.nickname
      userQQ.value.photo = res.data.figureurl_1
    })
  }

  return { userQQ }
}

// 表单校验
const useValidateForm = () => {
  // 表单数据
  const formData = reactive({
    mobile: '',
    code: ''
  })

  // 校验规则
  const rules = {
    mobile: schema.mobile,
    code: schema.code
  }

  return { formData, rules }
}

// 发送验证码
const useSendCode = (formData) => {
  // form表单实例
  const form = ref(null)
  const { start, count } = useCountDown(60)
  // 点击发送验证码按钮
  const sendCode = async () => {
    // console.log(234)
    // 校验手机号
    const validate = schema.mobile(formData.mobile)
    if (validate === true) {
      // 手机号正确 validate是布尔值
      // 判断是否正在发送 count.value===0(没有发送) count.value!==0(正在发送)
      if (count.value === 0) {
        try {
          // 调用接口
          await userQQBindCode(formData.mobile)
          // console.log(res)
          // 提示
          message({
            type: 'success',
            text: '发送成功'
          })
          // 开始倒计时
          start()
        } catch (error) {
          message({
            type: 'error',
            text: error.response.data.message
          })
        }
      }
    } else {
      // 手机号不正确 提示 validate是错误信息
      // 失败，使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
      form.value.setFieldError('mobile', validate)
    }
  }

  return { form, sendCode, count }
}

// 绑定qq
const useSubmit = (form, props, formData) => {
  const store = useStore()
  const router = useRouter()
  const bindQQ = async () => {
    // 整体表单验证
    const res = await form.value.validate()
    if (res.valid) {
      // 验证通过
      try {
        // 调用接口
        const { result } = userQQBindLogin({
          unionId: props.unionId,
          ...formData
        })
        // 存储用户信息
        store.commit('user/setProfile', result)
        // 直接跳转至首页
        router.replace('/')
        // 成功提示
        message({
          type: 'success',
          text: 'QQ绑定成功'
        })
      } catch (error) {
        message({
          type: 'error',
          text: 'QQ绑定失败'
        })
      }
    }
  }

  return { bindQQ }
}
export default {
  name: 'CallbackBind',
  components: {
    Form,
    Field
  },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    const { userQQ } = useQQ()

    const { formData, rules } = useValidateForm()

    const { form, sendCode, count } = useSendCode(formData)

    const { bindQQ } = useSubmit(form, props, formData)

    return { userQQ, formData, rules, sendCode, form, count, bindQQ }
  }
}
</script>

<style scoped lang='less'>
.user-info {
    width: 320px;
    height: 70px;
    margin: 0 auto;
    display: flex;
    background: #f2f2f2;
    align-items: center;
    padding: 0 10px;
    margin-bottom: 25px;
    img {
      background: #f2f2f2;
      width: 50px;
      height: 50px;
    }
    p {
      padding-left: 10px;
    }
  }
  .code {
    position: absolute;
    right: 0;
    top: 0;
    line-height: 50px;
    width: 80px;
    color: #999;
    &:hover {
      cursor: pointer;
    }
  }
</style>
